import path from 'path'
import express from 'express'
import bodyParser from 'body-parser'
import * as dotenv from 'dotenv'
import expressRateLimit from 'express-rate-limit'
import userRouter from './routes/userRoutes'
// 日志工具
import logger from './utils/logger'
const app = express()
const limiter = expressRateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟内
  max: 500, // 最大100次请求
})

app.use(express.static('public'))
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(bodyParser.text({ type: '*/xml' }))
// 不同环境使用不同环境变量
if (process.env.NODE_ENV === 'development') {
  dotenv.config({ path: path.join(__dirname, '../.env') })
}
else {
  dotenv.config({ path: path.join(__dirname, '../.env.prod') })
}
// 顺序跨域
app.all('*', (_, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*')
  res.setHeader('Access-Control-Allow-Headers', 'authorization, Content-Type')
  res.setHeader('Access-Control-Allow-Methods', '*')
  const { method, url, body } = _
  logger.info('method:', method, ',url:', decodeURI(url), ',body:', body)
  next()
})

app.use('/api', limiter)
app.use('/api/user/', userRouter)
app.set('trust proxy', 1)

const port = 3002
app.listen(port, () => globalThis.console.log(`Server is running on port ${port}`))
